import { FC, useEffect, useCallback } from 'react';
import { observer, useLocalStore } from 'mobx-react';
import { Form, Input, Button } from 'antd';
import type { FormInstance } from 'antd/lib/form';

import Icons from '@components/Icons';
import notification from '@utils/notification';
import { resetPasswordStore } from '@/stores/ResetPassword';

/** 定时器 */
let active: any;

const SureAccountForm: FC = () => {
  const [sureAccountForm] = Form.useForm<FormInstance>();
  const parentStore = useLocalStore(() => resetPasswordStore);
  const myStore = useLocalStore(() => ({
    /** 展示倒计时文字 */
    showCountDownText: false,
    /** 倒计时(s) */
    countDown: 60
  }));

  const handleSetSureAccountForm = useCallback(
    (form: FormInstance) => parentStore.setSureAccountForm(form),
    []
  );

  const handleClearInterval = useCallback(() => {
    myStore.showCountDownText = false;
    myStore.countDown = 60;
    clearInterval(active);
  }, []);

  useEffect(() => {
    handleClearInterval();
    handleSetSureAccountForm(sureAccountForm);
  }, [handleClearInterval, handleSetSureAccountForm, sureAccountForm]);

  /** 倒计时 */
  const handleCountingDown = useCallback(() => {
    active = setInterval(() => {
      if (myStore.countDown <= 1) {
        // 倒计时结束(不展示倒计时, 倒计时重置, 清除计时器)
        handleClearInterval();
      } else {
        myStore.countDown = myStore.countDown - 1;
      }
    }, 1000);
  }, [handleClearInterval]);

  /** 发送邮箱验证码 */
  const handleSendEmail = useCallback(async () => {
    // 未输入账户|邮箱/邮箱不合规
    const fields = await sureAccountForm.validateFields(['username', 'email']);

    // 校验账户和邮箱是否匹配
    // const validateFlag = await validateAccountAndEmail({ ...fields });
    // if(!validateFlag) {
    //   notification.error({
    //     message: '账户与邮箱不匹配, 请检查!',
    //   })
    // };

    // 不允许多次发送邮件
    if (myStore.showCountDownText) return;

    // 点击成功(展示倒计时)
    myStore.showCountDownText = true;
    handleCountingDown();

    // 给邮箱发送验证码
    // const res = await sendEmailCode({ email: fields.email });
    if (fields) {
      notification.success({
        message: '发送成功, 请填写收到的验证码!'
      });
    }
  }, [handleCountingDown, sureAccountForm]);

  return (
    <Form
      name="rb-find-password-first"
      form={sureAccountForm}
      initialValues={parentStore.sureAccountFormInitValues}
      wrapperCol={{ offset: 3, span: 18 }}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: '请输入账户名'
          }
        ]}
        hasFeedback
      >
        <Input
          prefix={<Icons type="UserOutlined" style={{ color: 'rgb(24, 144, 255)' }} />}
          placeholder="账户名"
        />
      </Form.Item>
      <Form.Item
        name="email"
        rules={[
          {
            required: true,
            message: '请输入此账户绑定的邮箱'
          },
          {
            type: 'email',
            message: '请输入有效的邮箱'
          }
        ]}
        hasFeedback
      >
        <Input
          prefix={<Icons type="MailOutlined" style={{ color: 'rgb(24, 144, 255)' }} />}
          placeholder="此账户绑定的邮箱"
        />
      </Form.Item>
      <Form.Item
        name="emailCode"
        rules={[
          {
            required: true,
            message: '请输入邮箱验证码'
          }
        ]}
      >
        <Input
          prefix={<Icons type="EditOutlined" style={{ color: 'rgb(24, 144, 255)' }} />}
          placeholder="验证码"
          suffix={
            <Button type="link" size="small" onClick={handleSendEmail}>
              {myStore.showCountDownText ? (
                <span style={{ color: 'red' }}>{myStore.countDown}秒后重新发送</span>
              ) : (
                '发送验证码'
              )}
            </Button>
          }
        />
      </Form.Item>
    </Form>
  );
};

export default observer(SureAccountForm);
